<template>
  <div>
    <el-form ref="form" :rules="rules" :model="form" label-width="100px">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="form.name" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model="form.code" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select v-model="form.manager" placeholder="请选择">
          <el-option
            v-for="item in employess"
            :key="item.id"
            :label="item.username"
            :value="item.username"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model="form.introduce" type="textarea" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="deptsSubmit">确定</el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getEmployeeSimple, addDepartments, getDepartDetail, updateDepartments } from '@/api/departments'
export default {
  name: 'DeptDialog',
  props: {
    parentId: {
      type: [Number, String],
      required: true
    },
    isEdit: {
      type: Boolean,
      required: true
    },
    originList: {
      type: Array,
      required: true
    }
  },
  data() {
    // 自定义验证编码 -- 整个模块不允许重复
    const validCode = (rule, value, callback) => {
      var existCodeList = this.originList.map(item => item.code)
      // 编辑状态 需要编辑的这一项排除在外
      if (this.isEdit) {
        // 使用 filter 方法筛选出 id 不一致的那一项，这时候只剩余 15 项
      // 将筛选出来 15 项中的 code 取出来形成一个新的数组
        existCodeList = this.originList.filter(data => data.id !== this.parentId).map(item => item.code)
      }
      existCodeList.includes(value) ? callback(new Error(`部门编码${value}重复`)) : callback()
    }
    // 验证名称 -- 同级部门名称不允许重复
    const validName = (rule, value, callback) => {
      var existNameList = this.originList.filter(data => data.pid === this.parentId).map(item => item.name)
      // 编辑状态
      if (this.isEdit) {
        // 找到编辑部门的本身
        const dept = this.originList.find(item => item.id === this.parentId)
        // 本身的pid
        const pid = dept.pid
        // 找到同级部门,并排除自己
        existNameList = this.originList.filter(item => item.pid === pid && item.id !== this.parentId).map(item => item.name)
      }
      existNameList.includes(value) ? callback(new Error(`本部门${value}已存在,请重新输入`)) : callback()
    }
    return {
      form: {
        code: '', // 部门编码
        introduce: '', // 介绍
        manager: '', // 负责人名称
        name: '' // 部门名称
      },
      employess: [], // 负责人基本资料
      // 验证规则
      rules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '部门名称要求1-50个字符', trigger: 'blur' },
          { validator: validName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '部门编码要求1-50个字符', trigger: 'blur' },
          { validator: validCode, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '部门负责人不能为空', trigger: 'blur' }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: 'blur' },
          { min: 1, max: 300, message: '部门介绍要求1-300个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    // 当前部门数据
    this.getDepartDetail()
    // 获取员工简单列表
    this.getEmployeeSimple()
  },
  methods: {
    // 根据ID查询部门详情
    async getDepartDetail() {
      if (this.isEdit) {
        const res = await getDepartDetail(this.parentId)
        this.form = res.data
      }
    },
    // 获取员工简单列表
    async getEmployeeSimple() {
      const res = await getEmployeeSimple()
      // console.log(res)
      this.employess = res.data
    },
    // 新增部门
    async addDepts() {
      const res = await addDepartments({
        ...this.form, pid: this.parentId
      })
      // console.log(res)
      // 提示
      if (!res.success) return this.$message.error(res.message)
      this.$message.success(res.message)
      // 父级关闭弹窗
      // 父级重新刷新列表
      this.$emit('updateList')
    },
    // 编辑部门
    async editDepts() {
      const res = await updateDepartments(this.form)
      // console.log(res)
      // 提示
      if (!res.success) return this.$message.error(res.message)
      this.$message.success(res.message)
      this.$emit('updateList')
    },
    // 点击确定
    deptsSubmit() {
      // 兜底验证
      this.$refs.form.validate((valid) => {
        if (!valid) return

        this.isEdit ? this.editDepts() : this.addDepts()
      })
    },
    // 取消按钮
    cancel() {
      // 父级关闭弹窗
      this.$emit('close')
    }
  }
}
</script>

<style lang="scss" scoped>
form.el-form {
  padding: 0rem 2.5rem 0rem 1.25rem;
}
.el-select {
  width: 100%;
}
</style>
